package cn.layfolk.daimao.config;

import cn.hutool.json.JSONUtil;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述: 无效 token 异常类
 * 作者: panhongtong
 * 创建时间: 2020-12-03 10:34
 **/
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = e.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        ResponseVo responseVo = new ResponseVo();
        responseVo.setStatusCode(401);
        if (cause instanceof InvalidTokenException) {
            // 无效令牌响应
            responseVo.setMessage("令牌无效！");
        } else if (cause instanceof InsufficientAuthenticationException) {
            responseVo.setMessage("未携带令牌");
        } else {
            // 其他异常
            responseVo.setMessage("令牌缺失！");
            e.printStackTrace();
        }
        response.getWriter().write(JSONUtil.toJsonStr(responseVo));
    }
}
